﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

//驱动Sevenstar CS200A 上位机，驱动指令参考相关文档

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private string receiveData;

        static UInt32 receiveBytesCount = 0;
        static UInt32 sendBytesCount = 0;

        public Form1()
        {
            InitializeComponent();
            serialPort1.Encoding = Encoding.GetEncoding("GB2312");  //串口接收编码
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;   //进程有关
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SearchAndAddSerialToComboBox(serialPort1, comboBox1);//搜索端口
            //串口接收功能打开
            comboBox1.Text = "COM5";
            comboBox2.Text = "9600";
            comboBox3.Text = "None";
            comboBox4.Text = "8";
            comboBox5.Text = "1";

            serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);

        }

        //自动搜索电脑上可用端口并添加到下拉框中
        private void SearchAndAddSerialToComboBox(SerialPort MyPort, ComboBox MyBox)
        {                                             //将可用端口号添加到ComboBox
            string[] MyString = new string[20];       //最多容纳20个，太多会影响调试效率
            string Buffer;                            //缓存
            MyBox.Items.Clear();                      //清空ComboBox内容
            for (int i = 1; i < 20; i++)              //循环
            {
                try                                   //核心原理是依靠try和catch完成遍历
                {
                    Buffer = "COM" + i.ToString();
                    MyPort.PortName = Buffer;
                    MyPort.Open();                    //如果失败，后面的代码不会执行
                    MyString[i - 1] = Buffer;
                    MyBox.Items.Add(Buffer);          //打开成功，添加至下俩列表
                    MyPort.Close();                   //关闭
                }
                catch
                {

                }
            }
            MyBox.Text = MyString[0];                  //初始化
        }

        //打开端口
        private void Open_Serial_Port(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = comboBox1.Text;//将combox1 中的字符串作为串口名
                int baudrate;
                int.TryParse(comboBox2.Text, out baudrate);//将combox2中的string尝试转为int
                serialPort1.BaudRate = baudrate;//设置波特率
                serialPort1.Parity = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), comboBox3.Text);
                serialPort1.DataBits = Convert.ToInt16(comboBox4.Text);
                serialPort1.StopBits = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits), comboBox5.Text);
                serialPort1.Encoding = Encoding.Default;//设置串口编码为default：获取操作系统的当前 ANSI 代码页的编码。

                serialPort1.Open();
                button1.Enabled = false;
                button2.Enabled = true;

            }
            catch
            {
                MessageBox.Show("open serial error !");
            }
        }

        //关闭端口
        private void Close_Serial_Port(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
            }
            button1.Enabled = true;
            button2.Enabled = false;
        }

        //清空接收栏
        private void Clear_Receive_Box(object sender, EventArgs e)
        {
            textBox1.Text = "";
        }

        //接收数据
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //if (!radioButton3.Checked)
            //{
            //    textBox1.AppendText(serialPort1.ReadExisting());                                //串口类会自动处理汉字，所以不需要特别转换
            //}
            //else
            //{
            //    byte[] data = new byte[serialPort1.BytesToRead];                                //定义缓冲区，因为串口事件触发时有可能收到不止一个字节
            //    serialPort1.Read(data, 0, data.Length);
            //    foreach (byte Member in data)                                                   //遍历用法
            //    {
            //        string str = Convert.ToString(Member, 16).ToUpper();
            //        textBox1.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");
            //    }
            //}

            receiveData = serialPort1.ReadExisting();
            ShowData(receiveData);
            textBox1.AppendText("\r\n"); //换行
        }

        //显示数据
        private void ShowData(string text)
        {
            string receiveText = text;

            //更新接收字节数
            receiveBytesCount += (UInt32)receiveText.Length;
            //statusReceiveByteTextBlock.Text = receiveBytesCount.ToString();

            //没有关闭数据显示
            //if (stopShowingButton.IsChecked == false)
            //{
                //字符串显示
                if (checkBox1.Checked == false)
                {
                    textBox1.AppendText(receiveText);

                }
                else //16进制显示
                {
                    byte[] recData = System.Text.Encoding.Default.GetBytes(receiveText);// 将接受到的字符串据转化成数组；  

                    foreach (byte str in recData)
                    {
                        textBox1.AppendText(string.Format("{0:X2} ", str));
                    }
                }
            //}

        }

        //向MCU发送控制字
        private void Send_Control_Bit(object sender, EventArgs e)
        {
            //向MCU发送单个控制字
            //byte[] Data = new byte[1];                                                         //单字节发数据     
            //if (serialPort1.IsOpen)
            //{
            //    if (textBox2.Text != "")
            //    {
            //        if (!radioButton1.Checked)
            //        {
            //            try
            //            {
            //                serialPort1.Write(textBox2.Text);
            //                //serialPort1.WriteLine();                             //字符串写入
            //            }
            //            catch
            //            {
            //                MessageBox.Show("串口数据写入错误", "错误");
            //            }
            //        }
            //        else                                                                    //数据模式
            //        {
            //            try                                                                 //如果此时用户输入字符串中含有非法字符（字母，汉字，符号等等，try，catch块可以捕捉并提示）
            //            {
            //                for (int i = 0; i < (textBox2.Text.Length - textBox2.Text.Length % 2) / 2; i++)//转换偶数个
            //                {
            //                    Data[0] = Convert.ToByte(textBox2.Text.Substring(i * 2, 2), 16);           //转换
            //                    serialPort1.Write(Data, 0, 1);
            //                }
            //                if (textBox2.Text.Length % 2 != 0)
            //                {
            //                    Data[0] = Convert.ToByte(textBox2.Text.Substring(textBox2.Text.Length - 1, 1), 16);//单独处理最后一个字符
            //                    serialPort1.Write(Data, 0, 1);                              //写入
            //                }
            //                //Data = Convert.ToByte(textBox2.Text.Substring(textBox2.Text.Length - 1, 1), 16);
            //                //  }
            //            }
            //            catch
            //            {
            //                MessageBox.Show("数据转换错误，请输入数字。", "错误");
            //            }
            //        }
            //    }
            //}
            //向MCU发送多个控制字
            if (!serialPort1.IsOpen)
            {
                MessageBox.Show("open serial !");
                return;
            }
            try
            {
                string sendData = textBox2.Text;    //复制发送数据

                //字符串发送
                if (checkBox2.Checked == false)
                {
                    serialPort1.Write(sendData);

                    //更新发送数据计数
                    sendBytesCount += (UInt32)sendData.Length;
                }
                else //十六进制发送
                {
                    try
                    {
                        sendData.Replace("0x", "");   //去掉0x
                        sendData.Replace("0X", "");   //去掉0X
                                                      //  sendData.


                        string[] strArray = sendData.Split(new char[] { ',', '，', '\r', '\n', ' ', '\t' });
                        int decNum = 0;
                        int i = 0;
                        byte[] sendBuffer = new byte[strArray.Length];  //发送数据缓冲区

                        foreach (string str in strArray)
                        {
                            try
                            {
                                decNum = Convert.ToInt16(str, 16);
                                sendBuffer[i] = Convert.ToByte(decNum);
                                i++;
                            }
                            catch
                            {
                                //MessageBox.Show("字节越界，请逐个字节输入！", "Error");                          
                            }
                        }

                        serialPort1.Write(sendBuffer, 0, sendBuffer.Length);

                        //更新发送数据计数
                        sendBytesCount += (UInt32)sendBuffer.Length;
                    }
                    catch //无法转为16进制时
                    {
                        MessageBox.Show("input 16 (0X) data !");
                        return;
                    }

                }

            }
            catch
            {

            }
        }

    }
}
